<?php

namespace app\controller;

use app\BaseController;
use app\model\AdminModel;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Session;
use think\Request;
use app\middleware\Check;
use think\facade\Validate;
use think\response\Json;
use think\validate\ValidateRule;
/**
 * Class School 管理端 学校控制器
 * @package app\controller
 */
class School extends BaseController
{
    protected $middleware = [Check::class];

    /**学校列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function school_list(Request $request)
    {
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            $input['limit'] = $request->post('limit');//每页显示数量
            $input['page'] = $request->post('page');//当前页
            $input['plat_id'] = $request->post('plat_id');//平台id
            $input['operate_id'] = $request->post('operate_id');//运营方id
            // 参数校验
            $validate = Validate::rule([
                'limit' => ValidateRule::isRequire(null, '缺少参数'),
                'page' => ValidateRule::isRequire(null, '缺少参数'),
                'plat_id' => function ($value) {
                    return $value === null ? '缺少参数' : true;
                },
                'operate_id' => function ($value) {
                    return $value === null ? '缺少参数' : true;
                }
            ]);
            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            // 获取管理员类型
            $redis = new \Redis();
            $config = config('tools.redis');
            $redis->connect($config['host'], $config['port']);
            $adminId = $redis->get($request->post('token'));
            if (!$adminId) return jsonFail('请先登录');
            $adminInfo = Db::table('eb_admin')->field('status,type')->find($adminId);
            if (!$adminInfo) return jsonFail('未知的管理员信息');
            if ($adminInfo['status'] != 1) return jsonFail('当前管理员无法操作');
            $map = [];
            $field = 'id,name,logo, FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time';
            switch ($adminInfo['type']) {
                case 1: // 超管
                    $field .= ', delivery, percentage, `limit`, company, plat, operate, extension';
                    if ($input['plat_id'] != '') $map[] = ['plat_id', '=', $input['plat_id']];
                    if ($input['operate_id'] != '') $map[] = ['operate_id', '=', $input['operate_id']];
                    break;
                case 2: // 平台方
                    $map[] = ['plat_id', '=', $adminId];
                    if ($input['operate_id'] != '') $map[] = ['operate_id', '=', $input['operate_id']];
                    break;
                case 3: // 运营方
                    $map[] = ['operate_id', '=', $adminId];
                    break;
            }
            $table = Db::table('eb_school')->field($field)->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('获取成功', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'list' => $list]);
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 简单学校列表
     * @param Request $request
     */
    public function simple_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $data = Db::table('eb_school')->field('id,name')->select()->toArray();
        return jsonSuccess('获取成功！', ['data' => $data]);
    }

    /** 添加学校
     * @param Request $request
     */
    public function increase(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        //获取登录管理员身份
        $admin =Admin_find($token);
        if($admin['type']!=1) return jsonFail('暂未权限操作，请联系系统管理员');
        $name = $request->param('name');//联系人
        $logo = $request->param('logo');//qq
        $delivery = $request->param('delivery');//固定配送费
        $percentage = $request->param('percentage');//超过限制块百分比
        $limit = $request->param('limit');//配送费加成限额
        $company = $request->param('company');//公司百分比
        $plat = $request->param('plat');//平台方百分比
        $operate = $request->param('operate');//运营方百分比
        $extension = $request->param('extension');//推广反比
        $plat_id = $request->param('plat_id');//平台方id
        $operate_id = $request->param('operate_id');//运营方id
        if (empty($logo)||empty($name)||empty($delivery)||empty($percentage)||empty($limit)||empty($company)||empty($plat)||empty($operate)||empty($extension)) return jsonFail('缺少参数');
        //判断是否有管理员
        $school_find = Db::table('eb_school')->where('name',$name)->find();
        if(!empty($school_find)) return jsonFail('学校名重复');
        $res = Db::table('eb_school')->insertGetId([
            'name' => $name,
            'logo' => $logo,
            'delivery' => $delivery,
            'percentage' => $percentage,
            'limit'=>$limit,
            'company'=>$company,
            'plat'=>$plat,
            'operate'=>$operate,
            'extension'=>$extension,
            'plat_id' => $plat_id,
            'operate_id' => $operate_id,
            'create_time' => time(),
        ]);
        if ($res) return jsonSuccess('添加成功！');
    }

    /**删除学校
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function delete_school(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        //获取登录管理员身份
        $admin =Admin_find($token);
        if($admin['type']!=1) return jsonFail('暂未权限操作，请联系系统管理员');
        $id = $request->param('id');//资方ID
        $res = Db::table('eb_school')->where('id', $id)->delete();
        if ($res) return jsonSuccess('删除成功！');
        return jsonFail('删除失败');
    }

    /**根据ID获取学校信息
     * @param Request $request
     */
    public function school_find(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $id = $request->param('id');//资方ID
        $data = Db::table('eb_school')->where('id', $id)->find();
        return jsonSuccess('获取成功！', $data);
    }

    /**编辑保存学校
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function school_edit(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        //获取登录管理员身份
        $admin =Admin_find($token);
        if($admin['type']!=1) return jsonFail('暂未权限操作，请联系系统管理员');
        $id = $request->param('id');//id
        $name = $request->param('name');//联系人
        $logo = $request->param('logo');//qq
        $delivery = $request->param('delivery');//固定配送费
        $percentage = $request->param('percentage');//超过限制块百分比
        $limit = $request->param('limit');//配送费加成限额
        $company = $request->param('company');//公司百分比
        $plat = $request->param('plat');//平台方百分比
        $operate = $request->param('operate');//运营方百分比
        $extension = $request->param('extension');//推广反比
        $plat_id = $request->param('plat_id');//平台方id
        $operate_id = $request->param('operate_id');//运营方id
        if (empty($logo)||empty($name)||empty($delivery)||empty($percentage)||empty($limit)||empty($company)||empty($plat)||empty($operate)||empty($extension)||empty($plat_id)||empty($operate_id)) return jsonFail('缺少参数');
        $res = Db::table('eb_school')->where('id', $id)->update([
            'name' => $name,
            'logo' => $logo,
            'delivery' => $delivery,
            'percentage' => $percentage,
            'limit'=>$limit,
            'company'=>$company,
            'plat'=>$plat,
            'operate'=>$operate,
            'extension'=>$extension,
            'plat_id'=>$plat_id,
            'operate_id'=>$operate_id,
        ]);
        if ($res == 0) return jsonFail('数据没有任何变化，不做更改！');
        if ($res) return jsonSuccess('编辑成功！');
    }

    //upload_img图片上传
    public function upload_img()
    {
        $mimeType = "jpg,png,JPG,JPEG,PNG,jpeg";
        $files = request()->file();
        try {
//            validate(['image' => 'fileSize:410241024|fileExt:jpg,png,jpeg'])->check($files);
            $savename = [];
            foreach ($files as $file) {
                $rule_size = 10*1048576;
                $size = $file->getSize();
                if ($size > $rule_size) {
                    return jsonFail('文件大于10M，不符合规范');
                }
                $type = explode('/', $file->getMime())[1];
                if (strpos($mimeType, $type) == false) {
                    return jsonFail('文件类型不符合，不符合规范');
                }
                $savename = \think\facade\Filesystem::disk('public')->putFile('', $file);
            }
//            $img = 'http://' . $_SERVER['SERVER_ADDR'] . 'uploads'.$savename;
             $data =  '/api/public/uploads/' . $savename;
            return jsonSuccess('上传成功',$data);
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    //删除图片
    public function delete_img(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $imgurl = $request->param('imgurl');//图片路径
        $id = $request->param('id');//编辑时ID
        $value= $request->param('value');//type：3时填写字段名字
        $type = $request->param('type');//1:eb_school  2:eb_goods 3：eb_user
        if (empty($imgurl)) return jsonFail('上传图片路径');
        $ex = '/api/';
        $count = strpos($imgurl, "$ex");
        $strlen = strlen($ex);
        $str = substr_replace($imgurl, "", $count, $strlen);
        $file = ROOT_PATH() . $str;
        if ($id && $type) {//删除数据库
            switch ($type) {
                case 1://1:eb_school  2:eb_goods
                    $res = Db::table('eb_school')->where('id', $id)->update(['logo' => '']);
                    break;
                case 2://2:eb_goods
                    $res = Db::table('eb_goods')->where('id', $id)->update(['pic' => '']);
                    break;
                case 3://2:eb_user
                    $res = Db::table('eb_user')->where('id', $id)->update([$value => '']);
                    break;
                case 4://2:eb_user
                    $res = Db::table('eb_category')->where('id', $id)->update(['pic' => '']);
                    break;
            }
        }
        if (!unlink($file)) {
            return jsonFail('删除失败！');
        } else {
            return jsonSuccess('删除成功！');
        }
    }

    /** 商户审核（列表）
     * @param Request $request
     * @return \think\response\Json
     */
    public function shop_list(Request $request)
    {
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            $token = $request->param('token');
            $admin =Admin_find($token);
            // 获取学校id
            $schoolId = Db::table('eb_school')->field('id')->where('operate_id', $admin['id'])->select()->toArray();
            if (!$schoolId) return jsonFail('获取学校信息失败');
            $limit = $this->request->param('limit');
            $page = $this->request->param('page');
            $table = Db::table('eb_school_store')->alias('a')
                ->leftJoin('eb_store b', 'a.store_id = b.id')
                ->where('a.school_id', 'in', array_column($schoolId,'id'));
            $count = $table->count();
            if ($count == 0)  return jsonSuccess('获取成功！', ['count' => 0, 'data' => []]);
            $data = $table->page($page,$limit)->order('b.create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'data' => $data]);
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 商户审核（修改状态）
     * @param Request $request
     * @return \think\response\Json
     */
    public function edit_shop(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $id = $request->param('id');//商户ID
        $status = $request->param('status');//0 未审核 1已审核 2审核未通过 3已禁用
        $remark = $request->param('remark');//备注
        if (empty($id)) return jsonFail('商户ID不能为空');
        if (empty($status)) return jsonFail('状态不能为空');
        if (empty($remark) && $status !=2) {//审核通过不用填备注
            $remark = '';
        }
        $res = Db::table('eb_store')->where('id', $id)->update(['status' => $status, 'remark' => $remark]);
        if ($res) return jsonSuccess('保存成功！');
    }

    /** 商户排序修改
     * @author tmx
     * @param Request $request
     * @return \think\response\Json
     */
    public function shop_sort(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $id = $request->param('id');//商户ID
        $sort = $request->param('sort');//排序
        if (empty($id)) return jsonFail('商户ID不能为空');
        if (empty($sort)) return jsonFail('排序不能为空');
        $res = Db::table('eb_store')->where('id', $id)->update(['sort' => $sort]);
        if ($res) {
            return jsonSuccess('修改成功！');
        } else {
            return jsonFail('请输入与原来不同的值');
        }
    }
    /** 用户审核（列表）
     * @param Request $request
     * @return \think\response\Json
     */
    public function user_list(Request $request)
    {
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            $token = $request->param('token');
            $admin =Admin_find($token);
            // 获取学校id
            $schoolId = Db::table('eb_school')->field('id')->where('operate_id', $admin['id'])->select()->toArray();
            if (!$schoolId) return jsonFail('获取学校信息失败');
            $limit = $this->request->param('limit');
            $page = $this->request->param('page');
            $table = Db::table('eb_user')->alias('u')
                ->leftJoin(['eb_school' => 's'], 's.id = u.school_id')
                ->leftJoin(['eb_dormitory' => 'd'], 'd.id = u.dormitory_id')
                ->field('u.id,u.type,u.account,u.name,u.phone,u.gender,u.create_time,s.name as school_name,d.name as dormitory_name,u.status,u.remark')
                ->where('u.school_id','in' , array_column($schoolId, 'id'));
            $count  = $table->count();
            if ($count == 0) return jsonSuccess('获取成功！', ['count' => $count, 'data' => []]);
            $data = $table->order('u.create_time', 'desc')->page($page,$limit)->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'data' => $data]);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return jsonFail('服务内部错误~');
        }
    }

    /** 用户审核（修改状态）
     * @param Request $request
     * @return \think\response\Json
     */
    public function edit_user(Request $request)
    {
        $id = $request->param('id');//商户ID
        $status = $request->param('status');//状态
        $remark = $request->param('remark');//备注
        if (empty($id)) return jsonFail('用户ID不能为空');
        if (empty($status)) return jsonFail('状态不能为空');
        if (empty($remark) && $status !=2) {//审核通过不用填备注
            $remark = '';
        }
        try {
            // 检测当前管理员状态
            $adminInfo = AdminModel::getInfo($request->post('token'), [1], [3]);
            if ($adminInfo instanceof Json) return $adminInfo;
            // 获取用户类型
            $type = Db::table('eb_user')->where('id', $id)->value('type');
            if ($type == 3) {
                Cache::store('redis')->handler()->zAdd('operate-'. $adminInfo['id'], 0, $id);
            }
            $res = Db::table('eb_user')->where('id', $id)->update(['status' => $status, 'remark' => $remark]);
            if ($res) return jsonSuccess('保存成功！');
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 分类列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function category_list(Request $request)
    {
        $token = $request->param('token');
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $limit = $this->request->param('limit');
        $page = $this->request->param('page');
        //$admin = Db::table('eb_admin')->where('id', $id)->find();
        if (empty($limit)) return jsonFail('缺少参数');
        if (empty($page)) return jsonFail('缺少参数');
        $data = Db::table('eb_category')->alias('a')
            ->page($page,$limit)
            ->select()->toArray();
        $count = Db::table('eb_category')
            ->count();
        return jsonSuccess('获取成功！', ['page' => $page, 'count' => $count, 'data' => $data]);
    }
    /** 分类添加
     * @param Request $request
     * @return \think\response\Json
     */
    public function category_inc(Request $request){
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $name = $this->request->param('name');//值
        $pic = $this->request->param('pic');//图片
        if (empty($name)) return jsonFail('缺少参数');
        if (empty($pic)) return jsonFail('缺少参数');
        if ($admin['type'] != 1) return jsonFail('暂未权限操作', []);
        try {
            $res = Db::table('eb_category')->insertGetId([
                'name'=>$name,
                'pic' => $pic
            ]);
            if($res)return jsonSuccess('添加成功');
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }

    }
    /** 分类编辑
     * @param Request $request
     * @return \think\response\Json
     */
    public function category_edit(Request $request){
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $id = $this->request->param('id');//ID
        if (empty($id)) return jsonFail('缺少参数');
        if ($admin['type'] != 1) return jsonFail('暂未权限操作', []);
        $data = Db::table('eb_category')->where('id',$id)->find();
        return jsonSuccess('获取成功',$data);
    }
    /** 分类编辑保存
     * @param Request $request
     * @return \think\response\Json
     */
    public function category_save(Request $request){
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $id = $this->request->param('id');//ID
        $name = $this->request->param('name');//name
        $pic = $this->request->param('pic');//图片
        if (empty($id)) return jsonFail('缺少参数');
        if (empty($name)) return jsonFail('缺少参数');
        if ($admin['type'] != 1) return jsonFail('暂未权限操作', []);
        try {
            $res = Db::table('eb_category')->where('id',$id)->update([
                'name'=>$name,
                'pic' => $pic
            ]);
            if ($res) return jsonSuccess('保存成功');
            return jsonFail('保存失败');
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }

    }
    /** 分类删除
     * @param Request $request
     * @return \think\response\Json
     */
    public function category_delete(Request $request){
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $id = $this->request->param('id');//ID
        if (empty($id)) return jsonFail('缺少参数');
        if ($admin['type'] != 1) return jsonFail('暂未权限操作', []);
        try {
            $res = Db::table('eb_category')->where('id',$id)->delete();
            if ($res) return jsonSuccess('删除成功');
            return jsonFail('删除失败');
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 经营范围列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function scope_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $limit = $this->request->param('limit');
        $page = $this->request->param('page');
        if (empty($limit)) return jsonFail('缺少参数');
        if (empty($page)) return jsonFail('缺少参数');
        $data = Db::table('eb_scope')
            ->page($page,$limit)
            ->select()->toArray();
        $count = Db::table('eb_scope')->alias('a')
            ->count();
        return jsonSuccess('获取成功！', ['page' => $page, 'count' => $count, 'data' => $data]);
    }
    /** 经营范围添加
     * @param Request $request
     * @return \think\response\Json
     */
    public function scope_inc(Request $request){
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $name = $this->request->param('name');//值
        if ($admin['type'] != 1) return jsonFail('暂未权限操作', []);
        try {
            $res = Db::table('eb_scope')->insertGetId([
                'name'=>$name
            ]);
            if ($res) return jsonSuccess('添加成功');
            return jsonFail('添加失败');
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }


    }
    /** 经营范围编辑
     * @param Request $request
     * @return \think\response\Json
     */
    public function scope_edit(Request $request){
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $id = $this->request->param('id');//ID
        if ($admin['type'] != 1) return jsonFail('暂未权限操作', []);
        $data = Db::table('eb_scope')->where('id',$id)->find();
        return jsonSuccess('获取成功',$data);
    }
    /** 经营范围编辑保存
     * @param Request $request
     * @return \think\response\Json
     */
    public function scope_save(Request $request){
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $id = $this->request->param('id');//ID
        $name = $this->request->param('name');//值
        if ($admin['type'] != 1) return jsonFail('暂未权限操作', []);
        try {
            $res = Db::table('eb_scope')->where('id',$id)->update([
                'name'=>$name,
            ]);
            if ($res) return jsonSuccess('保存成功');
            return jsonFail('保存失败');
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }

    }
    /** 经营范围删除
     * @param Request $request
     * @return \think\response\Json
     */
    public function scope_delete(Request $request){
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $token = $request->param('token');
        $admin =Admin_find($token);
        $id = $this->request->param('id');//ID
        if ($admin['type'] != 1) return jsonFail('暂未权限操作', []);
        try {
            $res = Db::table('eb_scope')->where('id',$id)->delete();
            if ($res) return jsonSuccess('删除成功');
            return jsonFail('删除失败');
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}
